<script setup lang="ts">
import LiuUserInfo from '@/components/LiuUserInfo.vue'
import type { TbMessage } from '@/types/messageapi'
import type { BaseDataResult, BaseResult, PageBean, PageVO } from '@/types/BaseResult'
import { Api } from '@/types/Api'
import { Tools } from '@/types/Tools'
import { useRouter } from 'vue-router'
const router = useRouter()

import {
  useMessage,
  NCard,
  NSkeleton,
  NSpace,
  NPopover,
  NButton,
  NSpin,
  NEl,
  NInput,
  NTabs,
  NTabPane,
  NForm,
  NFormItem,
  NModal,
  NDialog,
} from 'naive-ui'
import { onUnmounted } from 'vue'

const loading = ref(false)
const firstLoad = ref(true)

const message = useMessage()

//#region 富文本框
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
//@ts-expect-error 引入报错
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const mode = ref('default')
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  }, 1500)

  console.log('editorRef', editorRef.value, editorConfig)
})

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: Api.editorUrl(),
      fieldName: 'file',
      meta: {
        fileinfo: '富文本框上传图片',
      },
      //@ts-expect-error 引入报错
      customInsert(res, insertFn) {
        insertFn(Api.editorImageUrl(res.data.fid), '', Api.editorImageUrl(res.data.fid))
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

//@ts-expect-error 引入报错
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
//#endregion

//#region 查询
const page = ref({ pageNumber: 1, pageSize: 10 } as PageBean)
const list = ref([] as TbMessage[])
const queryInfo = ref({ order: 1, info: '' })

const query = () => {
  loading.value = true
  Api.get(
    `/message/${page.value.pageSize}/${page.value.pageNumber}/${queryInfo.value.order}`,
    { info: queryInfo.value.info },
    (data: BaseDataResult<PageVO<TbMessage>>) => {
      loading.value = false
      if (data.success) {
        list.value = list.value.concat(data.data.list)
        page.value = data.data.pageBean
        firstLoad.value = false
        return
      }
      message.error(data.message)
    },
  )
}

const changeOrder = (order: number) => {
  queryInfo.value.order = order
  requery()
}

const search = () => {
  firstLoad.value = false
  page.value.pageNumber = 1
  list.value = []
  query()
}

const requery = () => {
  firstLoad.value = true
  page.value.pageNumber = 1
  queryInfo.value.info = ''
  list.value = []
  query()
}

const loadmore = () => {
  page.value.pageNumber++
  if (page.value.pageNumber > page.value.pageCount) {
    return
  }
  query()
}

//#endregion

//#region 赞
const likeNews = (mess: TbMessage) => {
  Api.post(`/message/praise/${mess.mid}`, {}, (data: BaseDataResult<number>) => {
    if (data.success) {
      mess.exInfo.praised = !mess.exInfo.praised
      return
    }
    message.error(data.message)
  })
}

//#endregion

//#region 滚动
const scroll = () => {
  if (loading.value) {
    return
  }
  if (isScrollToBottom()) {
    loadmore()
  }
}

const isScrollToBottom = () => {
  const scrollTop = document.documentElement.scrollTop || window.scrollY
  const sh = document.documentElement.scrollHeight
  const ch = document.documentElement.clientHeight
  return scrollTop + ch >= sh - 100
}

//#endregion

//#region 详情

const toDetail = (mid: number) => {
  router.push(`/message/${mid}`)
}

const toDetail2 = (uid: number) => {
  router.push(`/message/uid/${uid}`)
}

//#endregion

//#region 发帖

const avisible = ref(false)
const addInfo = ref({} as TbMessage)

const showAdd = () => {
  resetAdd()
  avisible.value = true
}

const resetAdd = () => {
  addInfo.value = { title: '', info: '' } as TbMessage
}

const add = () => {
  loading.value = true
  Api.post('/message', addInfo.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      message.success('添加成功')
      return
    }
    message.error(data.message)
  })
}

//#endregion

onMounted(() => {
  requery()
  window.addEventListener('scroll', scroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', scroll)
})
</script>

<template>
  <div>
    <NEl class="p-4 top-box">
      <div class="fs-2">留言板</div>
      <div>
        <NSpace>
          <NInput v-model:value="queryInfo.info" placeholder="标题搜索"></NInput>
          <NButton type="primary" @click="search">查询</NButton>
          <NButton type="info" @click="showAdd">发帖</NButton>
        </NSpace>
      </div>
      <LiuUserInfo></LiuUserInfo>
    </NEl>
  </div>

  <!-- 切换排序 -->
  <NTabs @update:value="changeOrder">
    <NTabPane name="1" tab="发帖时间"></NTabPane>
    <NTabPane name="2" tab="点赞数"></NTabPane>
    <NTabPane name="3" tab="评论数"></NTabPane>
    <NTabPane name="4" tab="点击量"></NTabPane>
  </NTabs>

  <div>
    <div v-for="d in list" :key="d.mid" class="mb-3">
      <NCard>
        <div>
          <div>
            <div @click="toDetail(d.mid)" class="fs-3">{{ d.title }}</div>
            <div @click="toDetail2(d.uid)">{{ d.user.info.nickname || d.user.user.username }}</div>
            -
            {{ Tools.formatDate(d.lastupdate, 'yyyy-MM-dd') }}
            点击量：{{ d.hits }}
          </div>
          <div>
            <NPopover trigger="hover">
              <span>点赞量：{{ d.praise }}</span>
              <template #trigger>
                <div @click="likeNews(d)" :class="{ active: d.exInfo.praised }">赞</div>
              </template>
            </NPopover>
          </div>
        </div>
      </NCard>
    </div>
  </div>

  <div v-if="loading && firstLoad">
    <div v-for="i in 10" :key="i" class="ml-20 mr-20 mb-2">
      <NCard>
        <NSkeleton text></NSkeleton>
        <NSkeleton text></NSkeleton>
      </NCard>
    </div>
  </div>

  <div class="p-4 tc" v-if="loading">
    <span><NSpin size="small"></NSpin>加载中。。。</span>
  </div>
  <div class="p-4 tc" v-if="page.pageNumber >= page.pageCount && !loading">到底了</div>

  <NModal v-model:show="avisible" title="添加">
    <NCard></NCard>
    <div>
      <NForm>
        <NFormItem>
          <NInput v-model:value="addInfo.title" placeholder="标题"></NInput>
        </NFormItem>
        <NFormItem>
          <div>
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden; width: auto"
              v-model="addInfo.info"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </NFormItem>
      </NForm>
      <div>
        <NButton :loading="loading" type="primary" @click="add">提交</NButton>
        <NButton type="error" @click="avisible = false">关闭</NButton>
      </div>
    </div>
  </NModal>
</template>

<style scoped lang="scss">
.top-box {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  position: sticky;
  top: 0px;
  z-index: 10;
  background-color: var(--body-color);
}

.vimg {
  display: block;
  height: 7vw;
}

.img-box {
  display: flex;
  gap: 1rem;
  > div {
    flex: 1;
  }
  img {
    display: block;
    aspect-ratio: 16/9;
    width: 100%;
    object-fit: cover;
  }
}

.simg-box {
  display: flex;
  gap: 1rem;
  img {
    display: block;
    width: 100%;
    aspect-ratio: 16/9;
    object-fit: cover;
  }
  > div:first-of-type {
    flex: 2;
  }
  > div:last-of-type {
    flex: 1;
  }
  .info {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
  }
}

.detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .active {
    color: #ff0000;
  }
}
</style>
